""" Compute the bargaining parameter

"""

import numpy as np
import pandas as pd
import json
import sys

try:
    get_myopic_bargaining = eval(sys.argv[1])
except:
    get_myopic_bargaining = True
print(f"get_myopic_bargaining = {get_myopic_bargaining}")

#%% READ IN DATA ------------------------------------------------------------------------
df_contracts = pd.read_csv('./data_py/processed/contracts_final.csv', index_col=[0])
df_contracts['fixture_date'] = pd.to_datetime(df_contracts['fixture_date'])

price_match_values_by_spec = dict()
for spec in ['low', 'mid', 'high']:
    # Get price component 3
    with open(f"./models/price_match/price_match_values_{spec}_3_month.json") as f:
        price_match_values_by_spec[spec] = np.array(json.load(f))

    # Apply to contracts
    df_contracts.loc[df_contracts['spec'] == spec, 'a'] = price_match_values_by_spec[spec]

#%% GET AVERAGE PRICE IN 2005 AND THE MEAN 'A' PARAMETER --------------------------------
price_mean = df_contracts.loc[
    df_contracts['fixture_date'].dt.year == 2005, 'day_rate'].mean()
a_mean = df_contracts.loc[
    df_contracts['fixture_date'].dt.year == 2005, 'a'].mean()

#%% INPUT A DATAFRAME OF US MARGINS FROM ANNUAL REPORTS ---------------------------------
"""
Look a public annual reports in 2005. Get Net Income (after tax) and OPEX.

Margins are: NI / (NI + OPEX)

Do not use oil majors since it is difficult to disentangle upstream/downstream margins.

W&T Offshore (from yahoo finance):
Net Income: 189
OPEX: 203

Apache (from yahoo finance):
Net Income: 2.62
OPEX: 2.067

Stone (from annual report):
Net Income: 137
OPEX: 404
"""

margin = pd.DataFrame([189/(189+203),
                       137/(137+404),
                       2.62/(2.62+2.067)],
                      index=['W&T Offshore', 'Stone Energy', 'Apache'],
                      columns=['margin'])

# Get the margin
margin_mean = margin.mean()

#%% COMPUTE THE BARGAINING PARAMETER ----------------------------------------------------
# Note that the a_mean parameter is already divided by e.g. (1+beta) for a 2 period
# contract and so is directly comparable to the price.

delta = 1 - (margin_mean * price_mean) / (price_mean - a_mean * (1 - margin_mean))

pd.Series(delta.values[0]).to_csv('./models/smm_input/delta.csv')

#%% NOW DO THE BARGAINING PARAMETER WITH A WELL OUTSIDE OPTION ADJUSTMENT ---------------
# (Note requires the original simulation to have already finished, hence the 'try')
if get_myopic_bargaining:
    for prob_exit in [0.5, 0.6, 0.7, 0.75, 0.8, 0.9, 0.95, 0.99]:
        print(prob_exit)
        non_myopic_dict = dict()
        non_myopic_dict['prob_exit'] = prob_exit
        non_myopic_dict['prob_match_contracts'] = dict()
        for spec in ['low', 'mid', 'high']:
            non_myopic_dict['prob_match_contracts'][spec] = pd.read_csv(
                f'./models/robustness/prob_match_predict_contracts_{spec}.csv',
                index_col=[0]
            )
            df_contracts.loc[df_contracts['spec'] == spec, 'prob_match'] \
                = np.array(non_myopic_dict['prob_match_contracts'][spec])

        #%% Get mean adjustment
        prob_match_mean = df_contracts.loc[
            df_contracts['fixture_date'].dt.year == 2005, 'prob_match'].mean()
        adjustment_mean = 1 - 0.99 * (1 - non_myopic_dict['prob_exit']) * prob_match_mean
        delta_adjusted_num = (1 - margin_mean) * price_mean - a_mean * (1 - margin_mean)
        delta_adjusted_denom = price_mean * adjustment_mean - a_mean * (1 - margin_mean)
        delta_adjusted = delta_adjusted_num / delta_adjusted_denom
        pd.Series(delta_adjusted.values[0]).to_csv(f'./models/robustness/delta_adjusted_{prob_exit}.csv')
